<script setup>
// 因为是公用组件，所以在组件内部获取接口数据
import { getGuessLikeAPI } from '@/utils/apis.js'
import { onMounted, ref } from 'vue';

	let guessLikeList = ref([])
	let data = ref({
		page: 1,
		pageSize: 10
	})
	// 结束标记
	let finish = ref(false)
	let getGuessLikeData = async() => {
		// 退出判断
		if(finish.value) return uni.$showMsg('没有更多数据了')
		
		let res = await getGuessLikeAPI(data.value)
		// guessLikeList.value = res.result.items
		guessLikeList.value = [...guessLikeList.value, ...res.result.items]
		// 这里页码加一 我之前没想到，还在想触底的时候怎么传值
		// res.result.pages是接口给过来的共有多少页
		if(data.value.page < res.result.pages){
			data.value.page++
		}else{
			finish.value = true
		}
		
	}

	// 组件挂载完毕加载数据
	onMounted(() => getGuessLikeData())
	
	// 定义重置数据的方法,首页页面下拉刷新的时候用到
	let resetData = () => {
		data.value.page = 1
		guessLikeList.value = []
		finish.value = false
	}
	
	// 把方法暴露出去给父组件使用
	defineExpose({
		getGuessLikeData,
		resetData
	})
	
</script>

<template>
	<!-- 猜你喜欢 -->
	<view class="caption">
		<text class="text">猜你喜欢</text>
	</view>
	<view class="guess">
		<navigator class="guess-item" v-for="item in guessLikeList" :key="item.id" :url="`/pages/goods/goods?id=${item.id}`">
			<image class="image" mode="aspectFill"
				:src="item.picture"></image>
			<view class="name">{{item.name}}</view>
			<view class="price">
				<text class="small">¥</text>
				<text>{{item.price}}</text>
			</view>
		</navigator>
	</view>
	<view class="loading-text">{{finish ? '没有更多数据了' : '正在加载中...'}}</view>
</template>

<style lang="scss">
	:host {
		display: block;
	}

	/* 分类标题 */
	.caption {
		display: flex;
		justify-content: center;
		line-height: 1;
		padding: 36rpx 0 40rpx;
		font-size: 32rpx;
		color: #262626;

		.text {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 0 28rpx 0 30rpx;

			&::before,
			&::after {
				content: '';
				width: 20rpx;
				height: 20rpx;
				background-image: url(@/static/images/bubble.png);
				background-size: contain;
				margin: 0 10rpx;
			}
		}
	}

	/* 猜你喜欢 */
	.guess {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0 20rpx;

		.guess-item {
			width: 345rpx;
			padding: 24rpx 20rpx 20rpx;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			overflow: hidden;
			background-color: #fff;
			box-sizing: border-box;
		}

		.image {
			width: 304rpx;
			height: 304rpx;
		}

		.name {
			height: 75rpx;
			margin: 10rpx 0;
			font-size: 26rpx;
			color: #262626;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
		}

		.price {
			line-height: 1;
			padding-top: 4rpx;
			color: #cf4444;
			font-size: 26rpx;
		}

		.small {
			font-size: 80%;
		}
	}

	// 加载提示文字
	.loading-text {
		text-align: center;
		font-size: 28rpx;
		color: #666;
		padding: 20rpx 0;
	}
</style>